package com.flute.search.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class PrefixSearchService extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String prefixSearchIP;
	private int prefixSearchPort;
	private String serviceName;

	@Override
	public void init() throws ServletException {
		super.init();
		this.prefixSearchIP = this.getInitParameter("prefixSearchIP");
		this.prefixSearchPort = Integer.parseInt(this
				.getInitParameter("prefixSearchPort"));
		this.serviceName = this.getInitParameter("serviceName");
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String type = req.getParameter("type");
		String keyword = req.getParameter("keyword").trim();
		StringBuffer sb = new StringBuffer();
		if (keyword != null && !"".equals(keyword)) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpHost targetHost = new HttpHost(this.prefixSearchIP,
					this.prefixSearchPort, "http");
			HttpGet httpget = new HttpGet("/"
					+ this.serviceName.replaceAll("/", "")
					+ "/autosearcher?type=" + type + "&keyword="
					+ keyword.replace(" ", "+"));
			HttpResponse response = httpclient.execute(targetHost, httpget);
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				line = splitString(line);
				if (line != null) {
					sb.append("<div class='prefixLine'>" + line + "</div>");
				}
			}
		}
		System.out.println(sb);
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().print(sb);
	}

	private String splitString(String str) {
		if (str.trim().contains("<word><![CDATA[")) {
			return str.trim().replace("<word><![CDATA[", "")
					.replace("]]></word>", "");
		}
		return null;
	}
}
